<template>
    <div class="app-container">
        <el-row :gutter="24">
            <el-col :span="8">
                <el-tree :expand-on-click-node="false" show-checkbox
                        :data="treeData" :props="defaultProps" node-key="key"
                        :default-checked-keys="pages"
                        @node-click="onSelect"
                        @check-change="handleCheckChange">
                </el-tree>
            </el-col>
            <el-col :span="16">
                <div class="clearfix">
                    <span style="display:inline-block;margin:0;">按钮权限配置(当前页面：
                        <span>
                            <el-tag >{{pageName !== undefined ? pageName : '未选择' }}</el-tag>
                        </span>
                        )
                    </span>
                </div>
                <el-divider></el-divider>
                <!-- 表格列表 -->
                <el-table v-loading="permissionLoading" :data="permissionDataShow" ref="multipleTable" @selection-change="handleSelectionChange" >
                    <el-table-column type="selection" width="55"  align="center" />
                    <el-table-column label="权限名称" align="center" prop="permissionName"/>
                    <el-table-column label="按钮权限标识" align="center" prop="permissionCode"/>
                    <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
                </el-table>
                <!-- 分页插件 -->
                <pagination
                        v-show="permissionDataShow.length>0"
                        :total="permissionDataShow.length"
                        :page.sync="currentPage"
                        :limit.sync="pageSize"
                />
                <div class="clearfix" style="margin-top: 10px;">
                    <span style="display:inline-block;margin:0;">已有权限：
                        <template v-if="rolePermissionNameData.length > 0">
                          <el-tag v-for="item in rolePermissionNameData" :key="item.id" type="success" style="marginTop:8px;margin-right: 10px;">{{ item.name }}</el-tag>
                        </template>
                        <template v-else>无</template>
                    </span>
                </div>
                <el-divider></el-divider>
                <div class="dialog-footer" style="float:right;margin-top: 10px;">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>

            </el-col>
        </el-row>
    </div>
</template>

<script>
    import {asyncRoutes} from '@/router'
    import {saveroleaccess, getSinglePage} from '@/api/platform/role'
    import {getPageButtonPermission , getRolePageButtonPermission,editRolePageButtonPermission} from "@/api/platform/buttonPermission";

    export default {
        name: "grantAuth",
        props: {
            // 角色代码
            roleCode: String,
        },
        data() {
            return {
                buttonLoading: false,
                treeData: [],
                defaultProps: {
                    children: "children",
                    label: "title"
                },
                pageCode: '',
                pageName: undefined,
                pageKey: [],
                permissionSelectedRowKeys: [], // 选中的权限ID
                pages: [], // 选中的页面path
                // 权限加载效果
                permissionLoading: false,
                // 权限列表
                permissionDataShow: [],
                // 角色所属权限列表
                rolePermissionData: [],
                // 已有权限名称
                rolePermissionNameData: [],
                samePermissionList: [], // 已有权限
                // 分页
                currentPage: 1,
                currentIndex: '',
                pageSize: 10,
            }
        },
        watch: {

        },
        mounted() {
            // 遍历获取菜单列表 treeData
            asyncRoutes.forEach(element => {
                if ('meta' in element) {
                    const page = {
                        title: element.meta.title,
                        key: element.path,
                        pageCode: element.name
                    }
                    if ('children' in element) {
                        page.children = []
                        // page.disabled = true
                        element.children.forEach(ele => {
                            if ('meta' in ele) {
                                const chid = []
                                // let disable = false
                                if ('children' in ele) {
                                    // disable = true
                                    ele.children.forEach(ele2 => {
                                        chid.push({
                                            title: ele2.meta.title,
                                            key: ele2.path,
                                            pageCode: ele2.name
                                        })
                                    })
                                }
                                page.children.push({
                                    title: ele.meta.title,
                                    key: ele.path,
                                    pageCode: ele.name,
                                    // disabled: disable,
                                    children: chid
                                })
                            }
                        })
                    }
                    this.treeData.push(page)
                }
            })
            console.log(this.treeData)
        },
        created() {
            this.getNowPage();
        },
        methods: {
            // 获取当前角色所有页面权限
            getNowPage() {
                // console.log(this.roleCode)
                getSinglePage(this.roleCode).then(res => {
                    // console.log(res, this.roleCode)
                    if (res.retCode === '200') {
                        // console.log(res)
                        this.pages = []
                        res.responseBody.aRoleAuthDTO.forEach(element => {
                            this.pages.push(element.page)
                        })
                    } else {
                        console.log(res)
                        this.$message.error('失败！  错误号：' + res.retCode)
                    }
                })
            },

            // 菜单列表选择菜单
            onSelect(selectedKeys, info) {
                console.log('selectedKeys', selectedKeys)
                console.log('info', info)
                this.pageCode = info.data.pageCode // 获取页面编码
                this.pageKey = selectedKeys // path
                this.pageName = info.data.title
                this.samePermissionList = [] // 清空上一个页面选中的权限
                console.log('pageCode', this.pageCode)
                // console.log('path', this.pageKey)
                this.getPermissionList()
                this.getRolePermissions()
            },
            // 获取页面的按钮权限列表
            getPermissionList() {
                this.permissionLoading = true;
                getPageButtonPermission({
                    'searchParams': {
                        'pageCode': this.pageCode
                    }
                }).then(res => {
                    if (res.retCode === '200') {
                        this.permissionDataShow = res.responseBody
                        // 获取角色在该页面下已有的权限
                        this.getRolePermissions()
                    } else {
                        this.$message.error('获取数据失败，请刷新重试')
                    }
                })
            },
            // 获取角色在该页面下已有的权限
            getRolePermissions() {
                getRolePageButtonPermission({
                    'searchParams': {
                        'roleCode': this.roleCode,
                        'pageCode': this.pageCode,
                        'isBlackList': '1'
                    }
                }).then(res => {
                    if (res.retCode === '200') {
                        this.rolePermissionData = res.responseBody
                        //判断角色有哪些权限
                        this.getRolePermissionsList()
                        this.permissionLoading = false;
                    } else {
                        this.$message.error('获取已有权限数据失败，请刷新重试')
                    }
                })
            },

            // 判断角色有哪些权限
            getRolePermissionsList() {
                // console.log('permissionDataShow---', this.permissionDataShow)
                // console.log('rolePermissionData---', this.rolePermissionData)
                const permissionNameList = [];
                for (const i of this.permissionDataShow) {
                    for (const e of this.rolePermissionData) {
                        if (i.id === e.permissionId) {
                            const sameIdPermissionData = { id: i.id, name: i.permissionName }
                            // console.log('sameIdPermissionData', sameIdPermissionData)
                            permissionNameList.push(sameIdPermissionData)
                            this.samePermissionList.push(i);
                        }
                    }
                }
                this.rolePermissionNameData = permissionNameList
                // console.log('permissionNameList', permissionNameList)
                this.samePermissionList.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row,true);
                })
            },

            // 树控组件多选框选中数组
            handleCheckChange(data, checked, indeterminate) {
                console.log(data, checked, indeterminate);
                if (checked === true) {
                    this.pages.push(data.key);
                }else {
                    let arr = this.pages;
                    let id1 = arr.findIndex((arr) => arr == data.key);
                    this.pages.splice(id1,1);
                }
            },

            // 多选框选中数据
            handleSelectionChange(selection) {
                // console.log("==232=="+JSON.stringify(selection));
                this.permissionSelectedRowKeys = selection.map(item => item.id)
            },

            submitForm() {
                // console.log("页面：",JSON.stringify(this.pages));
                // console.log("权限：",JSON.stringify(this.permissionSelectedRowKeys));
                // 页面配置
                if (this.pages.length > 0) {
                    this.buttonLoading = true;
                    const data = {
                        roleCode: this.roleCode,
                        page: this.pages
                    }
                    saveroleaccess(data).then(res => {
                        if (res.retCode === '200') {
                            this.$message.success('页面权限修改成功！')
                            this.cancel();
                        } else {
                            this.$message.error('页面权限修改失败！  错误号：' + res.retCode)
                            console.log(res)
                        }
                    }).finally(err => {
                        this.buttonLoading = false;
                    })
                } else {
                    this.$message.warning('这位朋友,你还没选择任何页面哦！');
                    this.buttonLoading = false;
                }

                if (this.pageCode) {
                    this.onButtonPermissionSubmit()
                }
            },
            // 按钮配置
            onButtonPermissionSubmit() {
                this.buttonLoading = true;
                const permissionParams = [{
                    isBlackList:'1',
                    pageCode: this.pageCode,
                    permissionIds: this.permissionSelectedRowKeys,
                    roleCode: this.roleCode
                }]
                editRolePageButtonPermission(permissionParams).then(res => {
                    if (res.retCode === '200') {
                        this.$message.success('按钮权限修改成功！')
                        // this.getRolePermissions()
                        // this.getRolePermissionsList()
                        this.cancel();
                    } else {
                        this.$message.error('按钮权限修改失败！  错误号：' + res.retCode)
                        console.log(res)
                    }
                }).finally(err => {
                    this.buttonLoading = false;
                })
            },

            cancel() {
                this.$emit("cancelDialog");
            }
        }
    }
</script>

<style scoped>

</style>
